<template>
  <div class="nodeAttrBox" id="mustshowoption">
    <!-- 表格列筛选设置 -->
    <tb-column-filter :all-columns="flowDesignDetailNodeAttrColumns" @updatecolumn="columns = $event">
    </tb-column-filter>
    <!-- 节点属性表格 -->
    <div class="nodeAttrTbBox commonTableSty">
      <a-table
        ref="nodeAttrTable"
        :columns="columns"
        :data-source="nodeInfoList"
        :pagination="false"
        :scroll="{ y: 400, x: 1000 }"
        row-key="flowElementId">
        <span slot="approverColumn">
          {{ $t('approver') }} <i class="requiredStar">*</i>
        </span>
        <!-- 自定义结果通知 -->
        <span slot="resultNoticeColumn">
          {{ $t('resultNotice') }}
          <question-mark-tip :tip-title="$t('resultNoticeTip')" :popupContainer="getPopupContainer">
          </question-mark-tip>
        </span>
        <!-- 自定义撤回通知 -->
        <span slot="canInstanceCancelNoticeColumn">
          {{ $t('cancelNotice') }}
          <question-mark-tip :tip-title="$t('cancelNoticeTip')" :popupContainer="getPopupContainer">
          </question-mark-tip>
        </span>
        <template slot="flowElementCode" slot-scope="text">
          <table-ellipsis :text="text || '-'"></table-ellipsis>
        </template>
        <template slot="flowElementName" slot-scope="text">
          <table-ellipsis :text="text || '-'"></table-ellipsis>
        </template>
         <span slot="processModeDesc">
          {{ $t('auditWay') }}
          <question-mark-tip
            :tip-title="$t('processModeDesc')"
            :popupContainer="getPopupContainer"
          ></question-mark-tip>
        </span>
        <template slot="approvalRole" slot-scope="text">
          <table-ellipsis :text="text || '-'"></table-ellipsis>
        </template>
        <template slot="approver" slot-scope="text,record">
          <a-select
            v-if="record.roleCandidatesName"
            v-model="record.selectedUserIds"
            show-search
            :mode="record.flowElementId === 'Activity_gcy_audit' ? 'default' : 'multiple'"
            :max-tag="1"
            :class="{ hasError: record.error }"
            :filter-option="filterOption"
            :getPopupContainer="getPopupContainer"
            @change="changeUserIds(record)"
            style="width: 100%;"
          >
            <a-select-option
              v-for="user in record.roleCandidates"
              :title="user.candidatesEmail"
              :key="user.candidateUserId"> {{ user.candidatesName }} [{{user.candidatesEmail}}] </a-select-option>
          </a-select>
          <div v-else>
            <!-- 是指定用户的时候 -->
            {{ record.assignee }}
          </div>
        </template>
        <template slot="canResultNotice" slot-scope="text">
          <table-ellipsis :text="$t(text === 1 ? 'opened' : text === 0 ?'closed':'-')"></table-ellipsis>
        </template>
        <template slot="canInstanceCancelNotice" slot-scope="text">
          <table-ellipsis :text="$t(text === 1 ? 'opened' : text === 0 ?'closed':'-')"></table-ellipsis>
        </template>
        <template slot="remark" slot-scope="text">
          <table-ellipsis :text="text || '-'"></table-ellipsis>
        </template>
      </a-table>
    </div>
  </div>
</template>
<script>
import { flowDesignDetailNodeAttrColumns } from './config/list'
import TbColumnFilter from '@/components/TbColumnFilter'
import tableEllipsis from '@/components/Ellipsis/TableEllipsis'
import QuestionMarkTip from '@/views/components/QuestionMarkTip'
import flowDesignApi from '@/api/modules/flowManage/flowDesign'
export default {
  props: {
    methodName: {
      type: String,
      default: ''
    },
    applyUserName: {
      type: String,
      default: ''
    },
    // 是否需要缓存当前的操作
    cacheRequired: {
      type: Boolean,
      default: false
    },
    // 应用之前草稿指定的用户
    candidate: {
      type: Array,
      default () {
        return []
      }
    }
  },
  components: {
    TbColumnFilter,
    tableEllipsis,
    QuestionMarkTip
  },
  data () {
    return {
      columns: [],
      flowDesignDetailNodeAttrColumns,
      nodeInfoList: [],
      // 节点的审批用户 {节点名:审批用户ids}
      nodeOfApprovalObj: {}
    }
  },
  computed: {
    spyhInfo () {
      const { candidate, nodeInfoList } = this
      return {
        candidate,
        nodeInfoList
      }
    }
  },
  watch:{
    applyUserName:{
      handler(val){
        if(val){
          this.nodeInfoList.unshift({
            // "flowElementId": "Activity_1jm9w66",
            // "candidateType": "APPOINT_EL",
            "flowElementName": "申请人",
            "canResultNotice": '',
            "canInstanceCancelNotice": '',
            "assignee":this.applyUserName,
            // "roleCandidatesName": "管理员",
            "roleCandidates": null,
            "processModeDesc": "-"
          })
        }
      },
      immediate:true
    },
    spyhInfo: {
      handler (val) {
        if (val.candidate) {
          if (val.candidate.length > 0) { 
            val.nodeInfoList.forEach((item) => {
              val.candidate.forEach(item2 => {
                if (item.flowElementId === item2.flowElementId) {
                  item.selectedUserIds = item2.userIds
                }
              })
            })
          }
        }
      }
    }
  },
  created () {
    if (this.cacheRequired) {
      this.getConfigFromSession()
    } else {
      this.removeConfigFromSession()
    }
    this.initColumns()
    this.getAuditLists()
  },
  beforeDestroy () {
    if (this.cacheRequired) {
      this.saveConfigToSession()
    }
  },
  methods: {
    getPopupContainer () {
      return document.querySelector('#mustshowoption') || document.body
    },
    initColumns () {
      this.columns = flowDesignDetailNodeAttrColumns.map(item => {
        return {
          ...item
        }
      })
    },
    getAuditLists () {
      flowDesignApi[this.methodName] && flowDesignApi[this.methodName]().then(res => {
          const arr = res.data.map(item => {
          const selectedUserIds0 = this.nodeOfApprovalObj[item.flowElementId]
          const selectedUserIds = selectedUserIds0 ? [...selectedUserIds0] : []
          return {
            ...item,
            roleCandidates: item.roleCandidates ? (this.methodName=='getUserRegister'?[{candidateUserId:'all',candidatesName:"不指定人员，系统自动分配"},...item.roleCandidates]:[...item.roleCandidates]) : [],
            selectedUserIds,
            error: false
          }
        })
        this.nodeInfoList =[...this.nodeInfoList,...arr]
        // if (this.candidate.length > 0) {
        //   this.nodeInfoList.forEach((item) => {
        //     this.candidate.forEach(item2 => {
        //       if (item.flowElementId === item2.flowElementId) {
        //         // eslint-disable-next-line no-param-reassign
        //         item.selectedUserIds = item2.userIds
        //       }
        //     })
        //   })
        // }
      })
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 获取配置信息
    // eslint-disable-next-line consistent-return
    getConfigsData (noNeedValidate = false) {
      const checkResult = this.checkData(noNeedValidate)
      if (noNeedValidate) {
        return checkResult.candidates
      }
      if (!checkResult.success) {
        this.$message.error(this.$t('selectApprovalUserTip'))
        return checkResult.candidates
      }
      if (checkResult.success && (checkResult.candidates.length === 0)) {
        return 'noNeedRole'
      }
      console.log('@@@@@@checkResult.candidates',checkResult.candidates)
      return checkResult.candidates
    },
    // 检测需要设置审批用户列是否有设置
    checkData (noNeedValidate = false) {
      let flag = true
      const result = []
      if(this.methodName=='getUserRegister'){
        const data1=this.nodeInfoList[1]
        const data2=this.nodeInfoList[2]
        if(data1.selectedUserIds.includes('all')){
          const allIds=[]
          data1.roleCandidates.forEach(item=>{
            if(item.candidateUserId!=='all'){
              allIds.push(item.candidateUserId)
            }
          })
          data1.selectedUserIds=[...allIds]
        }
        if(data2.selectedUserIds.includes('all')){
          const allIds=[]
          data2.roleCandidates.forEach(item=>{
            if(item.candidateUserId!=='all'){
              allIds.push(item.candidateUserId)
            }
          })
          data2.selectedUserIds=[...allIds]
        }
      }
      if (noNeedValidate) {
        this.nodeInfoList.forEach(item => {
          if (item.roleCandidatesName) {
            //单选时转数组
            if (!(item.selectedUserIds instanceof Array)) {
              item.selectedUserIds = [item.selectedUserIds]
            }
            if (item.selectedUserIds.length > 0) {
              result.push({
                flowElementId: item.flowElementId,
                userIds: item.selectedUserIds
              })
            } else {
              result.push({
                flowElementId: item.flowElementId,
                userIds: []
              })
            }
          }
        })
      } else {
        this.nodeInfoList.forEach(item => {
          if (item.roleCandidatesName) {
            //单选时转数组
            if (!(item.selectedUserIds instanceof Array)) {
              item.selectedUserIds = [item.selectedUserIds]
            }
            if (item.roleCandidatesName && item.selectedUserIds.length === 0) {
              // eslint-disable-next-line no-param-reassign
              item.error = true
              flag = false
            } else {
              // eslint-disable-next-line no-param-reassign
              item.error = false
              item.selectedUserIds.length > 0 && result.push({
                flowElementId: item.flowElementId,
                userIds: item.selectedUserIds
              })
            }
          }
        })
      }
      return { success: flag, candidates: flag ? result : [] }
    },
    changeUserIds (record) {
      //单选时转数组
      let selectedUserIds = record.selectedUserIds;
      if(selectedUserIds && selectedUserIds.includes('all')){
        record.selectedUserIds=['all']
        selectedUserIds=['all']
      }
      this.nodeOfApprovalObj[record.flowElementId] = (selectedUserIds instanceof Array) ? selectedUserIds : (selectedUserIds ? [selectedUserIds] : []);
      // eslint-disable-next-line no-param-reassign
      record.error = !selectedUserIds || selectedUserIds.length === 0
    },
    // 缓存当前设置，在有上一步与下一步场景下需要
    saveConfigToSession () {
      sessionStorage.setItem('nodeOfApprovalObj', JSON.stringify(this.nodeOfApprovalObj))
    },
    // 读取组存中节点审批用户设置数据
    getConfigFromSession () {
      const result = sessionStorage.getItem('nodeOfApprovalObj')
      this.nodeOfApprovalObj = result ? JSON.parse(result) : {}
    },
    removeConfigFromSession () {
      sessionStorage.removeItem('nodeOfApprovalObj')
    }
  }
}
</script>
<style>
.hasError .ant-select-selection {
  border-color: #f5222d;
}
</style>
